<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use JPush\Client as JPushClient;

class JPushService
{
    protected $client;

    public function __construct()
    {
        $this->client = new JPushClient(env('JPUSH_APP_KEY'), env('JPUSH_MASTER_SECRET'));
    }

    public function pushNotify($registration_id, $message)
    {
        try {
            $result = $this->client->push()
                ->setPlatform(['android', 'ios'])
                ->addRegistrationId($registration_id)
                ->setNotificationAlert($message['title'], $message['content'])
                ->send();
            if ($result['http_code'] == 200) {
                Log::info('极光推送成功');
            } else {
                Log::error('极光推送失败', $result);
            }
        } catch (\Exception $e) {
            Log::error('极光推送异常', (array)$e);
        }
    }


    public function pushNotifyToAll($message)
    {
        try {
            $result = $this->client->push()
                ->setPlatform('all')
                ->addAllAudience()
                ->setNotificationAlert($message['title'], $message['content'])
                ->send();
            if ($result['http_code'] == 200) {
                Log::info('极光推送成功');
            } else {
                Log::error('极光推送失败', $result);
            }
        } catch (\Exception $e) {
            Log::error('极光推送异常', (array)$e);
        }
    }

}
